#include <bits/stdc++.h>

using namespace std;
const int N = 310, INF = 0x3f3f3f3f; 
int dist[N][N], t[N][N];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int bfs()
{
	if(t[0][0] == INF) return 0;
	
	memset(dist, 0x3f, sizeof dist);
	
	
	
	queue<pair<int, int>> q;
	q.push({0, 0});
	dist[0][0] = 0;
	
	while(q.size())
	{
		auto a = q.front(); q.pop();
		int i = a.first, j = a.second;
		
		for(int k = 0; k < 4; k++)
		{
			int x = i + dx[k], y = j + dy[k];
			if(x < 0 || y < 0) continue;
			if(dist[x][y] != INF) continue;
			if(dist[i][j] + 1 >= t[x][y])continue;
			
			dist[x][y] = dist[i][j] + 1;	
				
			if(t[x][y] == INF) return dist[x][y];
			q.push({x,y});
		}
	}
	return -1;
}
int main()
{
	memset(t, 0x3f, sizeof t);
	int m; cin >> m;
	for(int i = 1; i <= m; i++)
	{
		int x, y, z; cin >> x >> y >> z;
		t[x][y] = min(t[x][y], z);
		for(int i = 0;i < 4; i++)
		{
			int a = x + dx[i], b = y + dy[i];
			if(a < 0 || b < 0) continue;
			t[a][b] = min(t[a][b], z);
		}
	}
	cout << bfs() << endl;
	
	return 0;
}
